import GpContainer from "@/components/GpContainer";
import GpFontIcon from "@/components/GpFontIcon";
import { useNavigateEventChannel } from "@/hooks/useNavigateEventChannel";
import { navigate } from "@/utils/navigation";
import { Button, Form, FormProps, Input, Text, View } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { useEffect } from "react";
import { useImmer } from "use-immer";

export default function Index() {
  const [state, setState] = useImmer<FieldEditStateSimple>({
    placeholder: "",
    navigationbarTitleText: "",
    showTip: false
  })
  const { eventChannel } = useNavigateEventChannel()
  useEffect(() => {
    eventChannel && eventChannel.once("getField", (s: FieldEditStateSimple) => {
      if (s) {
        setState({...state, ...s})
        Taro.setNavigationBarTitle({
          title: s.navigationbarTitleText
        })
      }
    })
  }, [])
  const handleSubmit: FormProps['onSubmit'] = ({detail: {value}}) => {
    if (!value!.content) {
      Taro.showToast({
        title: state.placeholder,
        icon: "none"
      })
      return
    }
    eventChannel && eventChannel.emit("receiveField", value!.content)
    navigate()
  }
  return (
    <GpContainer className="bg-white">
      {
        state.showTip
        ? (
        <View className="flex flex-row items-center box-border pl-[32px] pr-[40px] h-[84px] bg-[#FD9900]/8">
          <GpFontIcon name="icon-zhuyi" color="#FD9900" size={32} className="mr-[8px]" />
          <Text className="text-[28px] leading-[28px] text-[#FD9900] flex-1">
            {state.tip}
          </Text>
          <GpFontIcon name="icon-guanbi" color="#FD9900" size={48} className="ml-[8px]" onClick={() => setState(draft => {draft.showTip = false})} />
        </View>
        ) : null
      }
      <Form className="box-border px-[32px] flex flex-col mt-[8px]" onSubmit={handleSubmit}>
        <View className="border-b border-solid border-b-[#EEEEEE] py-[40px]">
          <Input name="content" placeholder={state.placeholder} maxlength={state.maxContent} className="border-0 outline-0 text-primary text-[32px]" value={state.content} onInput={({detail: { value }}) => {setState(draft => {draft.content = value})}} />
        </View>
        {
          state.maxContent
          ? (
          <View className="flex flex-row items-center justify-end text-[24px] mt-[24px]">
            <Text className="text-theme">{state.content?.length}</Text>
            <Text className="text-third">/{state.maxContent}</Text>
          </View>
          ) : null
        }
        <Button formType="submit" className="text-center bg-theme h-[80px] leading-[80px] box-border rounded-[64px] mt-[96px]">
          <Text className="text-white text-[32px]">保存</Text>
        </Button>
      </Form>
    </GpContainer>
  )
}
